package com.fpost.action;

import java.text.MessageFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.hibernate.HibernateException;

import com.fpost.constants.ActionConstants;
import com.fpost.domain.User;
import com.fpost.form.CreateAccountForm;
import com.fpost.manager.UserManager;
import com.fpost.security.CryptoUtils;
import com.fpost.util.ActionUtils;
import com.fpost.util.CommonUtils;
import com.fpost.util.DateUtil;

public class CreateAccountAction extends Action {
	
	private static Logger log = Logger.getLogger(CreateAccountAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;
				
		try {
			CreateAccountForm createAccountForm = (CreateAccountForm) form;

			String username = createAccountForm.getUsername();
			String password = createAccountForm.getPassword();
			String emailAddress = createAccountForm.getEmailAddress();
			
			String firstName = createAccountForm.getFirstName();
			String lastName = createAccountForm.getLastName();
					
			User newUser = new User();
			newUser.setUsername(username);		
			newUser.setPassword(CryptoUtils.getHash(password));
			newUser.setEmailAddress(emailAddress);
			newUser.setCreatedOn(DateUtil.getGMTCalendar().getTime());
			newUser.setFirstName(firstName);
			newUser.setLastName(lastName);				
			
			Long userId = new UserManager().save(newUser);
			ActionUtils.setErrorMessage(request, "info.account.successfully.created");
			forward = ActionConstants.SUCCESS;
			
		} catch (HibernateException e) {
			log.error(e.getMessage(), e);
			forward = ActionConstants.FAILURE;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			forward = ActionConstants.SYSTEM_FAILURE;
		}

		return mapping.findForward(forward);
	}	

}
